<template>
  <q-page class="q-pa-md">
    <q-btn class="float-right" color="primary" icon="arrow_back" outline title="返回" to="/" />
    <div class="q-pb-md text-h5">上车</div>
    <!--错误提示-->
    <q-banner class="text-white bg-red q-mb-md" dense inline-actions v-if="serverErrorMessage">
      {{ serverErrorMessage }}
      <template v-slot:action>
        <q-btn @click="serverErrorMessage = ''" dense flat icon="close" size="sm" />
      </template>
    </q-banner>
    <!--成功提示-->
    <q-banner class="text-white bg-green q-mb-md" dense inline-actions v-if="serverSuccessMessage">
      {{ serverSuccessMessage }}
      <template v-slot:action>
        <q-btn @click="serverSuccessMessage = ''" dense flat icon="close" size="sm" />
      </template>
    </q-banner>
    <!--一般提示-->
    <q-banner class="text-white bg-info q-mb-md" dense inline-actions v-if="serverInfoMessage">
      {{ serverInfoMessage }}
      <template v-slot:action>
        <q-btn @click="serverInfoMessage = ''" dense flat icon="close" size="sm" />
      </template>
    </q-banner>
    <div class="row q-col-gutter-sm col-12">
      <div class="col-12">
        <q-icon color="red" name="fas fa-asterisk" size="10px" />
        <span>提货单ID</span>
        <easy-input v-model="$d.shipmentId" :error="v$.shipmentId.$error" :error-message="e$(v$.shipmentId.$errors)"
          :loading="shipmentIdLoadingState" @focus="fx.ui.select" :disable="submittingState || shipmentIdLoadingState"
          ref="shipmentId" @keyup.enter="validateShipmentId"/>
      </div>
      <div class="col-12">
        <q-icon color="red" name="fas fa-asterisk" size="10px" />
        <span>箱号</span>
        <easy-input v-model="$d.caseId" :error="v$.caseId.$error" :error-message="e$(v$.caseId.$errors)"
          :loading="shipmentIdLoadingState" @focus="fx.ui.select" :disable="submittingState"
          ref="caseId" @keyup.enter="doLoad"/>
      </div>
      <div class="col-12">
        <q-btn class="full-width" color="primary" label="确定上车" @click="doLoad" :loading="submittingState" />
      </div>
    </div>
  </q-page>
</template>

<script lang="ts">
export default {
  name: 'LoadingUpStd'
}
</script>

<script lang="ts" setup>

import {computed, nextTick, reactive, ref} from 'vue'
import useVuelidate from '@vuelidate/core'
import {ShipmentStateForLoadingUp} from '../../defs/loadingUp'
import {playErrorSound, playBeepSound, playSuccessSound} from '@njt/wms/helper/audio'
import {QInput} from 'quasar'

let serverErrorMessage = ref('')
let serverSuccessMessage = ref('')
let serverInfoMessage = ref('')
let shipmentIdLoadingState = ref(false)
let submittingState = ref(false)

const $d = reactive({
  shipmentId: null as number | null,
  caseId: '',
  lastLoadedUpCaseId: ''
})

const validators = $f.validators
const rules = {
  shipmentId: {
    required: validators.required,
    int32: validators.int32
  },
  caseId: {
    required: validators.required
  }
}
const valResults = reactive({
  shipmentId: ''
})
const v$ = useVuelidate(rules, computed(() => $d), {$autoDirty:true, $externalResults: valResults})
// 获取提货单信息
const validateShipmentId = function () {
  $d.caseId = ''
  serverErrorMessage.value = ''
  serverInfoMessage.value = ''
  serverSuccessMessage.value = ''
  if ($d.shipmentId && /^[+-]?(0|[1-9]\d{0,9})$/.test(String($d.shipmentId))) {
    shipmentIdLoadingState.value = true
    let focusOnWhenDone = ''
    $f.axios
      .get<ShipmentStateForLoadingUp>(`/wms/work/order/get-shipment-state-for-loading-up/${$d.shipmentId}`)
      .then((resp) => {
        let data = resp.data
        if ((data.shipmentState as string) < '93') {
          if (data.caseCount === 0) {
            playErrorSound()
            valResults.shipmentId = '该提货单没有可上车箱'
            focusOnWhenDone = 'shipment'
          } else {
            void nextTick(() => {
              caseId.value && caseId.value.focus()
            })
            playBeepSound()
            serverInfoMessage.value = `该提货单共${data.caseCount}箱,已上车${data.loadedCaseCount}箱,未上车${data.caseCount-data.loadedCaseCount}箱`
          }
        } else {
          playErrorSound()
          valResults.shipmentId = '该提货单已完成上车'
          focusOnWhenDone = 'shipment'
        }
      })
      .catch((err) => {
        playErrorSound()
        serverErrorMessage.value = $f.getAxiosErrMsg(err)
        focusOnWhenDone = 'shipment'
      })
      .finally(() => {
        shipmentIdLoadingState.value = false
        if (focusOnWhenDone !== '') {
          void nextTick(() => {
            shipmentId.value && shipmentId.value.focus()
          })
        }
      })
  } else {
    playErrorSound()
    void nextTick(() => {
      shipmentId.value && shipmentId.value.focus()
    })
  }
}

const doLoad = function () {
  serverErrorMessage.value = ''
  serverInfoMessage.value = ''
  serverSuccessMessage.value = ''
  void v$.value
    .$validate()
    .then((valRes) => {
      if (valRes) {
        submittingState.value = true
        let params = {
          shipmentId: $d.shipmentId,
          caseId: $d.caseId
        }
        let focusOnWhenDone = ''
        $f.axios
          .post<ShipmentStateForLoadingUp>('/wms/work/order/do-loading-up',params)
          .then((resp) => {
            let isLoadedDone = resp.data.isLoadedDone
            $d.lastLoadedUpCaseId = $d.caseId
            serverSuccessMessage.value = `上车成功。该提货单共${resp.data.caseCount}箱,已上车${resp.data.loadedCaseCount}箱,
            未上车${resp.data.caseCount-resp.data.loadedCaseCount}箱`
            if (!isLoadedDone) {
              $d.caseId = ''
              focusOnWhenDone = 'caseId'
              playBeepSound()
            } else {
              $d.shipmentId = null
              $d.caseId = ''
              focusOnWhenDone = 'shipmentId'
              playSuccessSound()
            }
            v$.value.$reset()
          })
          .catch((err) => {
            playErrorSound()
            serverErrorMessage.value = $f.getAxiosErrMsg(err) + ($d.lastLoadedUpCaseId ? `,上一个上车成功的箱号为${$d.lastLoadedUpCaseId}`:'')
            focusOnWhenDone = 'caseId'
          })
          .finally(() => {
            submittingState.value = false
            if (focusOnWhenDone) {
              void nextTick(() => {
                caseId.value && caseId.value.focus()
              })
            }
          })
      } else {
        playErrorSound()
      }
    })
}

const shipmentId = ref<QInput | null>(null)
const caseId = ref<QInput | null>(null)

const e$ = $f.getFieldErrStr
const fx = $f
</script>


<style scoped>

</style>
